﻿using System.Globalization;
using System.Text.RegularExpressions;

namespace XiaoSe
{
    public static class ConvertEx
    {
        public static long IpAddressToLong(this string ipAddress)
        {
            const string sRegex = @"^[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}$";
            if (!Regex.Match(ipAddress, sRegex, RegexOptions.IgnoreCase).Success)
            {
                return 0;
            }
            var ipSplit = ipAddress.Split('.');
            var newIp = "";
            newIp += ipSplit[0];
            for (var i = 1; i < ipSplit.Length; i++)
            {
                if (ipSplit[i].Length == 1)
                {
                    newIp += "00" + ipSplit[i];
                }
                if (ipSplit[i].Length == 2)
                {
                    newIp += "0" + ipSplit[i];
                }
            }
            return long.Parse(newIp);
        }
        public static string LongToIpAddress(this long ipAddress)
        {
            var ip = ipAddress.ToString(CultureInfo.InvariantCulture);
            if (ip.Length < 10)
            {
                return "";
            }
            string ipNew = "";
            if (ip.Length == 10)
            {
                ip = "00" + ip;
            }
            if (ip.Length == 11)
            {
                ip = "0" + ip;
            }
            var temp = "";
            for (var i = 0; i < ip.Length; i++)
            {
                temp += ip[i];
                if (i % 3 != 2) continue;
                temp = temp.TrimStart('0');
                if (temp == "")
                {
                    temp = "0";
                }
                ipNew += temp + ".";
                temp = "";
            }
            ipNew = ipNew.TrimEnd('.');
            return ipNew;
        }
        public static int StringToInt32(this string str, int defaultValue)
        {
            int i;
            if (!int.TryParse(str, out i))
            {
                i = defaultValue;
            }
            return i;
        }
    }
}
